/**
 * 
 */
package edu.umd.clip.lm.util;

import java.io.IOException;
import java.util.Map.Entry;
import java.util.*;

/**
 * @author Denis Filimonov <den@cs.umd.edu>
 *
 */
public class DetachableOutputFileCache implements Observer {
	final static private Object dummy = new Object();
	
	private LRU<DetachableOutputStream, Object> lru;
	private static final int DEFAULT_MAX_OPEN_FILES = 800;
	
	public DetachableOutputFileCache() {
		this(DEFAULT_MAX_OPEN_FILES);
	}
	
	@SuppressWarnings("serial")
	public DetachableOutputFileCache(int maxOpenFiles) {
		this.lru = new LRU<DetachableOutputStream, Object>(maxOpenFiles) {
			@Override
			protected boolean removeEldestEntry(Entry<DetachableOutputStream, Object> eldest) {
				boolean result = super.removeEldestEntry(eldest);
				if (result) {
					try {
						eldest.getKey().detach();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				return result;
			}
		};
	}

	/* (non-Javadoc)
	 * @see java.util.Observer#update(java.util.Observable, java.lang.Object)
	 */
	@Override
	public void update(Observable o, Object arg) {
		DetachableOutputStream output = (DetachableOutputStream) arg;
		synchronized(lru) {
			lru.put(output, dummy);
		}
	}
}
